<template>
  <div class="version-history">
    <div class="version-header">
      <div class="header-left">
        <h3>
          <el-icon><Clock /></el-icon>
          版本历史
        </h3>
        <el-tag type="info" size="small">共 {{ versions.length }} 个版本</el-tag>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="saveCurrentVersion">
          <el-icon><DocumentAdd /></el-icon>
          保存当前版本
        </el-button>
        <el-button @click="showCompareDialog = true" :disabled="selectedVersions.length !== 2">
          <el-icon><Connection /></el-icon>
          对比版本
        </el-button>
      </div>
    </div>

    <el-divider />

    <!-- 版本列表 -->
    <div class="version-list">
      <div 
        v-for="(version, index) in sortedVersions" 
        :key="version.id"
        class="version-item"
        :class="{ 
          'is-current': version.id === currentVersionId,
          'is-selected': selectedVersions.includes(version.id)
        }"
      >
        <div class="version-checkbox">
          <el-checkbox 
            v-model="selectedVersions"
            :label="version.id"
            @change="handleVersionSelect"
          />
        </div>

        <div class="version-info" @click="previewVersion(version)">
          <div class="version-header-row">
            <div class="version-title">
              <span class="version-name">{{ version.name || `版本 ${versions.length - index}` }}</span>
              <el-tag v-if="version.id === currentVersionId" type="success" size="small">当前版本</el-tag>
              <el-tag v-if="version.isAutoSave" type="info" size="small">自动保存</el-tag>
            </div>
            <div class="version-actions">
              <el-button type="primary" text size="small" @click.stop="restoreVersion(version)">
                <el-icon><RefreshLeft /></el-icon>
                恢复
              </el-button>
              <el-button type="info" text size="small" @click.stop="previewVersion(version)">
                <el-icon><View /></el-icon>
                预览
              </el-button>
              <el-button 
                v-if="!version.isAutoSave" 
                type="danger" 
                text 
                size="small" 
                @click.stop="deleteVersion(version)"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </div>

          <div class="version-meta">
            <div class="meta-item">
              <el-icon><User /></el-icon>
              <span>{{ version.author || '系统' }}</span>
            </div>
            <div class="meta-item">
              <el-icon><Clock /></el-icon>
              <span>{{ formatTime(version.timestamp) }}</span>
            </div>
            <div v-if="version.description" class="meta-item full-width">
              <el-icon><Document /></el-icon>
              <span>{{ version.description }}</span>
            </div>
          </div>

          <div class="version-stats">
            <el-tag size="small" effect="plain">{{ version.componentCount || 0 }} 个组件</el-tag>
            <el-tag size="small" effect="plain">{{ getVersionSize(version) }}</el-tag>
            <el-tag v-if="index === 0" type="success" size="small">最新</el-tag>
          </div>
        </div>
      </div>

      <el-empty v-if="versions.length === 0" description="暂无历史版本" />
    </div>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="showPreviewDialog"
      :title="`预览版本：${previewingVersion?.name || '未命名'}`"
      width="90%"
      top="5vh"
      fullscreen
    >
      <div class="preview-content">
        <el-alert 
          title="这是历史版本的预览" 
          type="info" 
          :closable="false"
          style="margin-bottom: 20px"
        >
          <div>创建时间：{{ formatTime(previewingVersion?.timestamp) }}</div>
          <div v-if="previewingVersion?.description">说明：{{ previewingVersion.description }}</div>
        </el-alert>

        <div class="preview-data">
          <pre>{{ JSON.stringify(previewingVersion?.data, null, 2) }}</pre>
        </div>
      </div>
      <template #footer>
        <el-button @click="showPreviewDialog = false">关闭</el-button>
        <el-button type="primary" @click="restoreVersion(previewingVersion)">
          <el-icon><RefreshLeft /></el-icon>
          恢复此版本
        </el-button>
      </template>
    </el-dialog>

    <!-- 对比对话框 -->
    <el-dialog
      v-model="showCompareDialog"
      title="版本对比"
      width="90%"
      top="5vh"
    >
      <div class="compare-content">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="compare-panel">
              <h4>版本 A</h4>
              <el-select v-model="compareVersionA" placeholder="选择版本" style="width: 100%; margin-bottom: 15px">
                <el-option 
                  v-for="version in versions" 
                  :key="version.id"
                  :label="version.name || formatTime(version.timestamp)"
                  :value="version.id"
                />
              </el-select>
              <div class="version-data">
                <pre>{{ getVersionData(compareVersionA) }}</pre>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="compare-panel">
              <h4>版本 B</h4>
              <el-select v-model="compareVersionB" placeholder="选择版本" style="width: 100%; margin-bottom: 15px">
                <el-option 
                  v-for="version in versions" 
                  :key="version.id"
                  :label="version.name || formatTime(version.timestamp)"
                  :value="version.id"
                />
              </el-select>
              <div class="version-data">
                <pre>{{ getVersionData(compareVersionB) }}</pre>
              </div>
            </div>
          </el-col>
        </el-row>

        <el-divider />

        <div class="compare-result">
          <h4>差异分析</h4>
          <el-alert 
            v-if="!compareVersionA || !compareVersionB"
            title="请选择两个版本进行对比" 
            type="info" 
            :closable="false"
          />
          <div v-else class="diff-list">
            <div class="diff-item">
              <el-icon class="diff-icon added"><CirclePlus /></el-icon>
              新增组件：<strong>{{ compareResult.added }}</strong> 个
            </div>
            <div class="diff-item">
              <el-icon class="diff-icon removed"><CircleClose /></el-icon>
              删除组件：<strong>{{ compareResult.removed }}</strong> 个
            </div>
            <div class="diff-item">
              <el-icon class="diff-icon modified"><Edit /></el-icon>
              修改组件：<strong>{{ compareResult.modified }}</strong> 个
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="showCompareDialog = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 保存版本对话框 -->
    <el-dialog
      v-model="showSaveDialog"
      title="保存版本"
      width="500px"
    >
      <el-form label-width="80px">
        <el-form-item label="版本名称">
          <el-input v-model="newVersionName" placeholder="如：添加用户字段" />
        </el-form-item>
        <el-form-item label="版本说明">
          <el-input 
            v-model="newVersionDescription" 
            type="textarea"
            :rows="3"
            placeholder="描述本次修改内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSaveDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmSaveVersion">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Clock, DocumentAdd, Connection, RefreshLeft, View, Delete,
  User, Document, CirclePlus, CircleClose, Edit
} from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  currentData: {
    type: Object,
    required: true
  },
  currentVersionId: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue', 'restore', 'save'])

// 版本数据
const versions = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 排序后的版本（最新的在前）
const sortedVersions = computed(() => {
  return [...versions.value].sort((a, b) => b.timestamp - a.timestamp)
})

// 选中的版本
const selectedVersions = ref([])

// 对话框控制
const showPreviewDialog = ref(false)
const showCompareDialog = ref(false)
const showSaveDialog = ref(false)

// 预览版本
const previewingVersion = ref(null)

// 对比版本
const compareVersionA = ref('')
const compareVersionB = ref('')

// 新版本信息
const newVersionName = ref('')
const newVersionDescription = ref('')

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  // 1分钟内
  if (diff < 60000) {
    return '刚刚'
  }
  // 1小时内
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  }
  // 24小时内
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  }
  // 7天内
  if (diff < 604800000) {
    return `${Math.floor(diff / 86400000)}天前`
  }
  
  // 完整日期
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取版本大小
const getVersionSize = (version) => {
  const size = JSON.stringify(version.data).length
  if (size < 1024) return `${size}B`
  if (size < 1048576) return `${(size / 1024).toFixed(1)}KB`
  return `${(size / 1048576).toFixed(1)}MB`
}

// 保存当前版本
const saveCurrentVersion = () => {
  newVersionName.value = ''
  newVersionDescription.value = ''
  showSaveDialog.value = true
}

// 确认保存版本
const confirmSaveVersion = () => {
  const version = {
    id: Date.now().toString(),
    name: newVersionName.value,
    description: newVersionDescription.value,
    timestamp: Date.now(),
    author: '当前用户',
    data: JSON.parse(JSON.stringify(props.currentData)),
    componentCount: props.currentData.components?.length || 0,
    isAutoSave: false
  }
  
  versions.value.push(version)
  showSaveDialog.value = false
  ElMessage.success('版本保存成功')
  
  emit('save', version)
}

// 自动保存版本
const autoSave = () => {
  const version = {
    id: `auto_${Date.now()}`,
    name: '自动保存',
    description: '',
    timestamp: Date.now(),
    author: '系统',
    data: JSON.parse(JSON.stringify(props.currentData)),
    componentCount: props.currentData.components?.length || 0,
    isAutoSave: true
  }
  
  // 限制自动保存版本数量
  const autoSaveVersions = versions.value.filter(v => v.isAutoSave)
  if (autoSaveVersions.length >= 10) {
    // 删除最旧的自动保存版本
    const oldestAutoSave = autoSaveVersions.sort((a, b) => a.timestamp - b.timestamp)[0]
    const index = versions.value.findIndex(v => v.id === oldestAutoSave.id)
    if (index !== -1) {
      versions.value.splice(index, 1)
    }
  }
  
  versions.value.push(version)
}

// 恢复版本
const restoreVersion = (version) => {
  ElMessageBox.confirm(
    `确定要恢复到此版本吗？当前的更改将会丢失。`,
    '恢复版本',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    emit('restore', version)
    showPreviewDialog.value = false
    ElMessage.success('版本恢复成功')
  }).catch(() => {})
}

// 预览版本
const previewVersion = (version) => {
  previewingVersion.value = version
  showPreviewDialog.value = true
}

// 删除版本
const deleteVersion = (version) => {
  ElMessageBox.confirm(
    '确定要删除此版本吗？此操作不可恢复。',
    '删除版本',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = versions.value.findIndex(v => v.id === version.id)
    if (index !== -1) {
      versions.value.splice(index, 1)
      ElMessage.success('版本已删除')
    }
  }).catch(() => {})
}

// 处理版本选择
const handleVersionSelect = () => {
  // 限制只能选择两个版本
  if (selectedVersions.value.length > 2) {
    selectedVersions.value = selectedVersions.value.slice(-2)
  }
}

// 获取版本数据
const getVersionData = (versionId) => {
  const version = versions.value.find(v => v.id === versionId)
  if (!version) return ''
  return JSON.stringify(version.data, null, 2)
}

// 对比结果
const compareResult = computed(() => {
  if (!compareVersionA.value || !compareVersionB.value) {
    return { added: 0, removed: 0, modified: 0 }
  }
  
  const versionA = versions.value.find(v => v.id === compareVersionA.value)
  const versionB = versions.value.find(v => v.id === compareVersionB.value)
  
  if (!versionA || !versionB) {
    return { added: 0, removed: 0, modified: 0 }
  }
  
  const componentsA = versionA.data.components || []
  const componentsB = versionB.data.components || []
  
  // 简单对比（实际应该更复杂）
  const added = componentsB.length - componentsA.length
  const removed = added < 0 ? Math.abs(added) : 0
  
  return {
    added: added > 0 ? added : 0,
    removed,
    modified: Math.min(componentsA.length, componentsB.length)
  }
})

// 暴露方法给父组件
defineExpose({
  autoSave
})
</script>

<style scoped>
.version-history {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.version-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h3 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.version-list {
  flex: 1;
  overflow-y: auto;
  padding-right: 5px;
}

.version-item {
  display: flex;
  gap: 15px;
  padding: 15px;
  margin-bottom: 10px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s;
  cursor: pointer;
}

.version-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.2);
}

.version-item.is-current {
  border-color: #67c23a;
  background: #f0f9ff;
}

.version-item.is-selected {
  border-color: #409eff;
  background: #ecf5ff;
}

.version-checkbox {
  flex-shrink: 0;
  padding-top: 2px;
}

.version-info {
  flex: 1;
}

.version-header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.version-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.version-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.version-actions {
  display: flex;
  gap: 5px;
  opacity: 0;
  transition: opacity 0.3s;
}

.version-item:hover .version-actions {
  opacity: 1;
}

.version-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 10px;
  font-size: 13px;
  color: #909399;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.meta-item.full-width {
  width: 100%;
}

.version-stats {
  display: flex;
  gap: 8px;
}

/* 预览内容 */
.preview-content {
  max-height: 70vh;
  overflow-y: auto;
}

.preview-data {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  overflow-x: auto;
}

.preview-data pre {
  margin: 0;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 13px;
  line-height: 1.6;
}

/* 对比内容 */
.compare-content {
  max-height: 70vh;
  overflow-y: auto;
}

.compare-panel h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.version-data {
  height: 400px;
  overflow-y: auto;
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.version-data pre {
  margin: 0;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 13px;
  line-height: 1.6;
}

.compare-result {
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.compare-result h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.diff-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.diff-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

.diff-icon {
  font-size: 18px;
}

.diff-icon.added {
  color: #67c23a;
}

.diff-icon.removed {
  color: #f56c6c;
}

.diff-icon.modified {
  color: #e6a23c;
}

/* 滚动条 */
.version-list::-webkit-scrollbar {
  width: 6px;
}

.version-list::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.version-list::-webkit-scrollbar-thumb:hover {
  background: #c0c4cc;
}
</style>

